import CONFIG from './config.js'

class Message {
    constructor({text, size = 1, type = "info", duration, delay, is_stroke}) {
        this.text = text;
        this.size = size; // base size:30
        this.size_px = CONFIG.base_font_size * this.size;
        this.type = type; // info, warning

        duration = duration === 0 ? 0 : duration || 3;
        this.duration = duration * 1000; //seconds

        this.ts = new Date().getTime();
        this.delay = (delay && delay * 1000) || 0;
        this.is_stroke = is_stroke;
    }

    show(game, offset_y) {
        let ctx = game.stage_canvas_ctx;
        let width = game.map.map_info.width;

        ctx.textAlign = 'center';
        ctx.font = this.size_px + "px bold yahei";
        ctx.strokeStyle = ctx.fillStyle = this.type === "warning" ? "#d36a1d" : "#67940d";
        ctx.lineWidth = this.size;
        if (!this.is_stroke) {
            ctx.fillText(this.text, width / 2, offset_y + this.size_px * 0.8);
        } else {
            ctx.strokeText(this.text, width / 2, offset_y + this.size_px * 0.8);
        }
    };

    static show_msg(game) {
        let ts = new Date().getTime();
        let m_list = Message.message_list;
        let height = game.map.map_info.height;

        m_list = m_list.filter(function (msg) {
            return ts - msg.ts <= msg.duration + msg.delay || msg.duration === 0;
        });

        Message.message_list = m_list;

        m_list = m_list.filter(function (msg) {
            if (!msg.delay) return true;
            return ts - msg.ts > msg.delay;
        });

        let offset_y = m_list.length > 1 ? height / 4 : height / 3;
        m_list.forEach(function (msg) {
            msg.show(game, offset_y);
            offset_y += msg.size_px * 1.2;
        });

    };

    static add_message({text, size, type, duration, delay, is_stroke}, clear) {
        if (!Message.message_list) Message.message_list = [];
        if (clear) Message.clear_message();
        let message = new Message({text, size, type, duration, delay, is_stroke});
        Message.message_list.push(message);
    }

    static clear_message() {
        Message.message_list = [];
    }
}

export default Message;

